<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
 */

// use App\Service\DataResource;
use App\Singleton\Classes\QueuePush;
// use App\Singleton\Classes\Redis;
// use Hyperf\GoTask\MongoClient\MongoClient;
use Hyperf\AsyncQueue\JobInterface;
use Hyperf\ExceptionHandler\Formatter\FormatterInterface;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Snowflake\IdGeneratorInterface;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Amqp\Producer;

if (!function_exists('di')) {
    /**
     * Finds an entry of the container by its identifier and returns it.
     * @param null|mixed $id
     * @return mixed|\Psr\Container\ContainerInterface
     */
    function di($id = null)
    {
        $container = ApplicationContext::getContainer();
        if ($id) {
            return $container->get($id);
        }
        return $container;
    }
}

if (!function_exists('format_throwable')) {
    /**
     * Format a throwable to string.
     * @param Throwable $throwable
     * @return string
     */
    function format_throwable(Throwable $throwable): string
    {
        return di()->get(FormatterInterface::class)->format($throwable);
    }
}
if (!function_exists('rabbit_push')) {
    function rabbit_push($data)
    {
        return di()->get(Producer::class)->produce($data);
    }
}

if (!function_exists('queue_push')) {
    /**
     * Push a job to async queue.
     */
    function queue_push(JobInterface $job, int $delay = 0, string $key = 'default'): bool
    {
        return (new QueuePush)->push($job, $delay);
    }
}

if (!function_exists('redis')) {
    /**
     * Produce a redis produce
     */
    function redis()
    {
        return di(\Hyperf\Redis\Redis::class);
    }
}

// if (!function_exists('fastMongodb')) {
//     /**
//      * Produce a fastMongodb client
//      */
//     function mongodb2()
//     {
//         $db = env('MONGODB_DB', 'open');
//         $client = di(MongoClient::class);
//         return $client->$db;
//     }
// }
if (!function_exists('createId')) {
    /**
     * Produce a unique id
     */
    function createId(string $prefix = '')
    {
        $generator = di()->get(IdGeneratorInterface::class);
        return $prefix . $generator->generate();
    }
}
if (!function_exists('createULId')) {
    /**
     * Produce a unique id
     */
    function createULId(string $prefix = '')
    {
        $ulid = (new \Hidehalo\Nanoid\Client())->formattedId('0123456789abcdefghijklmnopqrstuvwxyz_');
        return $prefix . $ulid;
    }
}
if (!function_exists('mongodb')) {
    /**
     * Produce a mongodb client
     */
    function mongodb()
    {
        $client = new \MongoDB\Client('mongodb://root:Dragon8798520@main-mongodb.mongodb.rds.aliyuncs.com:3717,sec-mongodb.mongodb.rds.aliyuncs.com:3717/admin?replicaSet=mgset-29666173');
        return $client->kaifazhe;
    }
}
if (!function_exists('mongodb2')) {
    /**
     * Produce a mongodb client
     */
    function mongodb2()
    {
        $client = new \MongoDB\Client('mongodb://root:Dragon8798520@main-mongodb.mongodb.rds.aliyuncs.com:3717,sec-mongodb.mongodb.rds.aliyuncs.com:3717/admin?replicaSet=mgset-29666173');
        return $client->kaifazhe;
    }
}
if (!function_exists('addOperateLog')) {
    /**
     * Produce a unique id
     */
    function addOperateLog(array $operateData = [])
    {
        if (!empty($operateData)) {
            if (!isset($operateData['is_admin']) || empty($operateData['is_admin'])) {
                $operateData['is_admin'] = 0;
            }
            if (!isset($operateData['opstatus'])) {
                $operateData['opstatus'] = 1;
            }
            $operateData['time'] = time();
            $operateData['_id'] = createId('O');
            $operateData['ip'] =  (isset($operateData['ip'])) ? $operateData['ip'] : '0.0.0.0';
            mongodb2()->operatelog->insertOne($operateData);
        }
    }
}
if (!function_exists('requestFailLog')) {
    /**
     * write a request fail log
     */
    function requestFailLog($jsonData = '',$requestId = '')
    {
        // if (!empty($jsonData)) {
        //     $request = di()->get(RequestInterface::class);
        //     $logData['time'] = time();
        //     $logData['_id'] = (empty($requestId)) ? createId('RF') : $requestId;
        //     $logData['url'] = $request->fullUrl();
        //     $logData['url'] = str_replace('hyperfserver','api.web.ecapi.cn',$logData['url']);
        //     $logData['url'] = str_replace('atestserver','api.test.ecapi.cn',$logData['url']);
        //     $logData['content'] = (is_array($jsonData)) ? json_encode($jsonData,JSON_UNESCAPED_UNICODE) : $jsonData;
        //     $logData['ip'] =  getClientIp($request);
        //     mongodb2()->request_fail_log->insertOne($logData);
        //     unset($request,$logData);
        // }
    }
}
if (!function_exists('getClientIp')) {
    /**
     * Produce a unique id
     */
    function getClientIp(object $request)
    {
        if ($request) {
            $ipArr = $request->getHeader('x-real-ip');
            if (empty($ipArr)) {
                $ipArr = $request->getHeader('x-forwarded-for');
            }
            unset($request);
            if (isset($ipArr[0]) && !empty($ipArr[0])) {
                return $ipArr[0];
            } else {
                return '';
            }
        }
    }
}
